package cn.wsalix.admin.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.anlaser.service.impl.CommonServiceImpl;
import cn.anlaser.utils.SearchFilter;
import cn.anlaser.utils.SearchFilter.Operator;
import cn.wsalix.admin.entity.Quick;
import cn.wsalix.admin.entity.SysRole;
import cn.wsalix.admin.form.QuickForm;
import cn.wsalix.admin.repository.QuickRepository;
import cn.wsalix.admin.service.MenuService;
import cn.wsalix.admin.service.QuickService;
import cn.wsalix.constant.Global;
import cn.wsalix.exception.ExistException;
import cn.wsalix.init.RoleInit;

@Service("quickService")
public class QuickServiceImpl extends
		CommonServiceImpl<QuickForm, QuickRepository, Quick> implements
		QuickService {
	@Autowired
	private QuickRepository quickRepository;
	@Autowired
	private ExistException existException;
	@Autowired
	private MenuService menuService;
	@Autowired
	private RoleInit roleInit;
	@Override
	public String module() {
		return "/admin/quick";
	}

	@Override
	public QuickRepository getRepository() {
		return quickRepository;
	}

	@Override
	public Class<Quick> getEntityClazz() {
		return Quick.class;
	}

	@Transactional
	@Override
	public Quick add(QuickForm form) {
		if (isExistByCode(form.getCode())) {
			throw Global.getException("code.exist",
					existException.getCodeExist());
		}
		return super.add(form);
	}

	@Transactional
	@Override
	public Quick edit(QuickForm form) {
		if (isExistByCode(form.getCode())) {
			throw Global.getException("code.exist",
					existException.getCodeExist());
		}
		return super.edit(form);
	}

	private boolean isExistByCode(String code) {
		QuickForm form = new QuickForm();
		form.setCode(code);
		List<Quick> Quicks = findByForm(form);
		return !Quicks.isEmpty() && Quicks.size() > 0;
	}

	@Override
	public Map<String, SearchFilter> buildByForm(QuickForm form) {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		if (form.getCode() != null && !form.getCode().equals("")) {
			filters.put("code",
					new SearchFilter("code", Operator.EQ, form.getCode()));
		}
		if (form.getUserId() != null && !form.getUserId().equals("")) {
			filters.put("userId",
					new SearchFilter("userId", Operator.EQ, form.getUserId()));
		}
		return filters;
	}

	@Override
	public List<Quick> findByForm(SysRole role) {
		QuickForm form = new QuickForm();
		if (role == null) {
			role = roleInit.getClientRole();
		}
		form.setCode(role.getCode());
		List<Quick> quicks = findByForm(form);
		return quicks;
	}

}
